<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="_token" content="{{ csrf_token() }}"/>
    <title>商品添加</title>
    <link rel="stylesheet" href="{{ asset('admin/libs/layui/css/layui.css') }}"/>
    <link rel="stylesheet" href="{{ asset('admin/module/admin.css?v=316 ')}}"/>
    <script type="text/javascript" src="{{ asset('admin/libs/sku/jquery.min.js') }}"></script>
    <script type="text/javascript" src="{{ asset('admin/libs/sku/createSkuTable.js?v16') }}"></script>
    {{--<script type="text/javascript" src="{{ asset('admin/libs/sku/getSetSkuVals.js?1') }}"></script>--}}
    <script type="text/javascript" src="{{ asset('admin/libs/tinymce/tinymce.min.js') }}"></script>

    <script type="text/javascript" src="{{ asset('/admin/libs/layui/layui.js')}} "></script>
    <script type="text/javascript" src="{{ asset('/admin/js/common.js')}} "></script>

</head>
<style type="text/css">.layui-form-required:before {font-size: 12px;}</style>
<body>

<!-- 页面加载loading -->
<div class="page-loading">
    <div class="ball-loader">
        <span></span><span></span><span></span><span></span>
    </div>
</div>

<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 添加和修改公用的表单 -->
            <form id="EDStudentForm" lay-filter="EDStudentForm" class="layui-form model-form layui-row">
                <div class="layui-col-md6">

                    <div class="layui-form-item">
                        <label class="layui-form-label">商品名称</label>
                        <div class="layui-input-block">
                            <input name="name" placeholder="请输入商品名称" type="text" class="layui-input"
                                   lay-verType="tips"  />
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">产品分类</label>
                        <div class="layui-input-block">
                            <input name="category_all_id" placeholder="请选择产品分类" lay-verType="tips"  />
                        </div>
                    </div>


                    <div class="layui-form-item">
                        <label class="layui-form-label">首页大图</label>
                        <div class="layui-input-block">
                            <div id="strImg1"></div>
                            <button type="button" class="layui-btn" id="upload1">
                                <i class="layui-icon">&#xe67c;</i>上传图片
                            </button>
                            <input type="hidden" name="recom_image" id="recom_image" value="">
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">详情页主图</label>
                        <div class="layui-input-block">
                            <div id="strImg2"></div>
                            <button type="button" class="layui-btn" id="upload2">
                                <i class="layui-icon">&#xe67c;</i>上传图片
                            </button>
                            <input type="hidden" name="main_image" id="main_image" value="">
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">详情页多图</label>
                        <div class="layui-input-block">
                            <div class="layui-upload">
                                <button type="button" class="layui-btn layui-btn-normal" id="testList">选择多图</button>
                                <div class="layui-upload-list">
                                    <table class="layui-table">
                                        <thead>
                                        <tr><th>图片名</th>
                                            <th>大小</th>
                                            <th>状态</th>
                                            <th>操作</th>
                                        </tr></thead>
                                        <tbody id="demoList"></tbody>
                                    </table>
                                </div>
                                <button type="button" class="layui-btn" id="testListAction">开始上传</button>
                                <input type="hidden" id="task_att" name='multi_image' value="" />
                                {{--<input type="hidden" id="task_att_original" name='task_att_original' value="" />--}}
                            </div>

                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">商品类型</label>
                        <div class="layui-input-block">
                            <input type="radio" name="speci_type" value="0" title="单一" checked/>
                            <input type="radio" name="speci_type" value="1" title="多规格"/>
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">SKU-规格:</label>
                        <div class="layui-input-block">
                            @foreach($speci as $item)
                                <input type="checkbox"  lay-filter="speci" lay-skin="primary"  class="layui_checkbox speci" value="{{$item->id}}" title="{{$item->name}}" />
                            @endforeach
                        </div>
                    </div>
                    <div class="layui-form-item" id="appendStr">


                    </div>

                    <!--sku模板,用于克隆,生成自定义sku-->
                    <div id="skuCloneModel" style="display: none;">
                        <div class="clear"></div>
                        <ul class="SKU_TYPE">
                            <li is_required='0' propid='' sku-type-name="">
                                <a href="javascript:void(0);" class="delCusSkuType">移除</a>
                                <input type="text" class="cusSkuTypeInput"/>：
                            </li>
                        </ul>
                        <ul>
                            <li>
                                <input type="checkbox" class="model_sku_val" propvalid='' value=""/>
                                <input type="text" class="cusSkuValInput"/>
                            </li>
                        </ul>
                        <div class="clear"></div>
                    </div>
                    <div class="clear"></div>
                    <div id="skuTable">
                        <table class="skuTable">
                            <tbody>
                            </tbody>
                        </table>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">促销语</label>
                        <div class="layui-input-block">
                            <input name="promo_title" placeholder="请输入促销语" type="text" class="layui-input"
                                   lay-verType="tips"  />
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">标题</label>
                        <div class="layui-input-block">
                            <input name="title" placeholder="请输入标题" type="text" class="layui-input"
                                   lay-verType="tips"  />
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">单位</label>
                        <div class="layui-input-block">
                            <input name="pcs" placeholder="请输入pcs" type="text" class="layui-input"
                                   lay-verType="tips"  />
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">原价</label>
                        <div class="layui-input-block">
                            <input name="origi_price" placeholder="请输入原价" type="number" class="layui-input" maxlength="20"
                                   lay-verType="tips"  />
                        </div>
                    </div>


                    <div class="layui-form-item">
                        <label class="layui-form-label">价格</label>
                        <div class="layui-input-block">
                            <input name="price" placeholder="请输入价格" type="number" class="layui-input" maxlength="20"
                                   lay-verType="tips"  />
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">库存</label>
                        <div class="layui-input-block">
                            <input name="stock" placeholder="请输入库存" type="number" class="layui-input" maxlength="20"
                                   lay-verType="tips"  />
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">推荐首页</label>
                        <div class="layui-input-block">
                            <input type="radio" name="is_index" value="1" title="是" checked/>
                            <input type="radio" name="is_index" value="0" title="否"/>
                        </div>
                    </div>
                    <div class="layui-inline layui-col-md4">
                        <label class="layui-form-label layui-form-required">生产日期</label>
                        <div class="layui-input-block">
                            <input id="edtDateFormAdv2" name="produ_time" type="text" placeholder="请选择提醒时间"
                                   class="layui-input date-icon" autocomplete="off" lay-verType="tips"
                                    />
                        </div>
                    </div>
                </div>
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">商品详情</label>
                        <textarea id="demoEditor" name="content"></textarea>
                    </div>

                </div>
                <div class="layui-form-item text-right">
                    <button class="layui-btn layui-btn-primary" type="button" ew-event="closePageDialog">取消</button>
                    <button class="layui-btn" type="button" lay-filter="EDStudentModelSubmit" lay-submit>保存</button>
                </div>
            </form>
            <!-- 公用表单结束 -->
        </div>
    </div>
</div>


<script>
    layui.use(['layer', 'admin', 'form', 'table', 'laytpl', 'util', 'laydate', 'cascader', 'tagsInput', 'upload'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var admin = layui.admin;
        var form = layui.form;
        var table = layui.table;
        var laytpl = layui.laytpl;
        var util = layui.util;
        var laydate = layui.laydate;
        var cascader = layui.cascader;
        var upload = layui.upload;

        var demoListView = $('#demoList')
            ,uploadListIns = upload.render({
            elem: '#testList'
            ,url: "/admin/goods/upload" //改成您自己的上传接口。
            ,accept: 'file'
            ,multiple: true
                ,field:'file'//对应控制器中的第一行。$file = $request->file('file');***
            ,auto: false
            ,headers: {
                'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
            }
            ,bindAction: '#testListAction'
            ,choose: function(obj){
                var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                //读取本地文件
                obj.preview(function(index, file, result){
                    var tr = $(['<tr id="upload-'+ index +'">'
                        ,'<td>'+ file.name +'</td>'
                        ,'<td>'+ (file.size/1024).toFixed(1) +'kb</td>'
                        ,'<td>等待上传</td>'
                        ,'<td>'
                        ,'<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                        ,'<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                        ,'</td>'
                        ,'</tr>'].join(''));

                    //单个重传
                    tr.find('.demo-reload').on('click', function(){
                        obj.upload(index, file);
                    });

                    //删除
                    tr.find('.demo-delete').on('click', function(){
                        delete files[index]; //删除对应的文件
                        tr.remove();
                        uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                    });

                    demoListView.append(tr);
                });
            }
            ,done: function(res, index, upload){
                if(res.status){ //上传成功
                    //将文件名信息添加到隐藏的input框中。
                    //先获取现在的文件名，然后将上传的文件名追加到刚才的文件名中
                var newfilename = $('#task_att').val();
                    newfilename = newfilename=='' ? res.msg : newfilename + ',' + res.msg;
                    $("#task_att").val(newfilename);
                    var newfilename_original = $('#task_att_original').val();
                    newfilename_original = newfilename_original==''?res.originalname: newfilename_original + ',' + res.originalname;
                    $("#task_att_original").val(newfilename_original);


                    var tr = demoListView.find('tr#upload-'+ index)
                        ,tds = tr.children();
                    tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                    tds.eq(3).html('<image src="/'+res.msg+'"  >'); //清空操作
                    return delete this.files[index]; //删除文件队列已经上传成功的文件
                }
                this.error(index, upload);
            }
            ,error: function(index, upload){
                var tr = demoListView.find('tr#upload-'+ index)
                    ,tds = tr.children();
                tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
                tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
            }
        });

        // 图片上传-大图
        var uploadInst1 = upload.render({
            elem: '#upload1' //绑定元素
            ,url: '/admin/goods/upload' //上传接口
            ,field:'file'
            ,headers: {
                    'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                }
            ,done: function(res){
                var strImg1 = '<div> <image src=/'+res.msg+' style="width:80px;height: 80px;border: 5rpx;margin-bottom: 5px"></div>';
                $("#strImg1").append(strImg1);
                console.log(res)
                $("#recom_image").val(res.msg)
                //上传完毕回调
            }
            ,error: function(){
                //请求异常回调
            }
        });


        // 图片上传-详情页主图
        var uploadInst2 = upload.render({
            elem: '#upload2' //绑定元素
            ,url: '/admin/goods/upload' //上传接口
            ,field:'file'
            ,headers: {
                'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
            }
            ,done: function(res){
                var strImg2 = '<div> <image src=/'+res.msg+' style="width:80px;height: 80px;border: 5rpx;margin-bottom: 5px"></div>';
                $("#strImg2").append(strImg2);
                $("#main_image").val(res.msg)
                console.log(res)
                //上传完毕回调
            }
            ,error: function(){
                //请求异常回调
            }
        });

        laydate.render({
            elem: '#edtDateFormAdv2'
        });

        var s_ids=[];
        form.on('checkbox(speci)', function(data){

            if(data.elem.checked==true){
                s_ids.push(data.value)
            }else{
                var index = s_ids.indexOf(data.value);
                if (index > -1) {
                    s_ids.splice(index, 1);
                }
            }
            if(s_ids.length>0){

                $.ajax({

                    url:"/admin/goods/speci/getSpeciValues",
                    type:'post',
                    data: {id:s_ids},
                    dataType: 'json',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                    },
                    success:function(res){
                        if(res.code==200){
                            result = res.data;
                            console.log(result);
                            var str = ''
                            for(var j=0; j<result.length; j++){

                                str += '<ul class="SKU_TYPE">'
                                str +=        '<li style="width: 110px;text-align: right" is_required="1" propid='+result[j].speci.id+' sku-type-name="'+result[j].speci.name+'">'+result[j].speci.name+'：</li>'
                                str +=    '</ul>'
                                str +=    '<ul>'
                                        for(var m=0; m<result[j].speci_value.length; m++){
                                            str +=  '<li><label><input type="checkbox" style="display: block!important;" class="sku_value layui_checkbox" lay-skin="primary"  propvalid='+ result[j].speci_value[m].id +' value="'+result[j].speci_value[m].name+'"/>'+ result[j].speci_value[m].name +'</label></li>'
                                        }
                                str +=   '</ul>'
                                str +=   '<div class="clear"></div>'

                            }
                            $("#appendStr").empty()
                            $("#appendStr").append(str)
                            table.render()
                        }
                    }
                });

            }


        });

        // 工具条点击事件
        table.on('tool(demoTableED1)', function (obj) {
            var data = obj.data;
            var layEvent = obj.event;
            if (layEvent === 'comments') {  // 查看评论
                showComments(data.id);
            } else if (layEvent == 'view') {
                showInfo(data);
            } else if (layEvent == 'checkList') {
                openCheckList(data);
            }
        });

        // 表单提交事件
        form.on('submit(EDStudentModelSubmit)', function (data) {
            var res = [];

            $("tr[class*='sku_table_tr']").each(function(){
               var obj = {};
               obj.speci_value_ids = $(this).attr("propvalids");
               obj.price = $(this).find(".setting_sku_price").val();
               obj.stock = $(this).find(".setting_sku_stock").val();
               res.push(obj)
            });
            console.log(data.field)
            console.log(res)
            $.ajax({

                url:"/admin/goods/addGoods",
                type:'post',
                data: {'goods':data.field,'sku':res},
                dataType: 'json',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                },
                success:function(res){
                    console.log(res);
                    if(res.code==200){
                        layer.msg(res.msg, {icon: 1});

                    }
                }
            });

            //
            // layer.msg("表单验证通过", {icon: 1});
            // return false;
        });

        // 分类选择
        $.ajax({
            url: "/admin/goods/category/getTree",
            type: 'get',
            data: '',
            dataType: 'json',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
            },
            success: function (res) {
                if (res.code == 200) {
                    result = res.data;
                    console.log(result);
                    cascader.render({
                        elem: '#EDStudentForm input[name="category_all_id"]',
                        itemHeight: '220px',
                        data: result
                    })
                }
            }
        })


        // 渲染富文本编辑器
        tinymce.init({
            selector: '#demoEditor',
            height: 800,
            plugins: 'code print preview fullscreen paste searchreplace save autosave link autolink image imagetools media table codesample lists advlist hr charmap emoticons anchor directionality pagebreak quickbars nonbreaking visualblocks visualchars wordcount',
            toolbar: 'fullscreen preview code | undo redo | forecolor backcolor | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | outdent indent | numlist bullist | formatselect fontselect fontsizeselect | link image media emoticons charmap anchor pagebreak codesample | ltr rtl',
            toolbar_drawer: 'sliding',
            images_upload_handler: function (blobInfo, success, failure) {
                var xhr, formData;
                xhr = new XMLHttpRequest();
                xhr.withCredentials = false;
                xhr.open('POST', '/admin/goods/upload?from=1');
                var token = '{{ csrf_token() }}';
                xhr.setRequestHeader("X-CSRF-Token", token);
                xhr.onload = function() {
                    var json;
                    if (xhr.status != 200) {
                        failure('HTTP Error: ' + xhr.status);
                        return;
                    }
                    json = JSON.parse(xhr.responseText);

                    if (!json || typeof json.location != 'string') {
                        failure('Invalid JSON: ' + xhr.responseText);
                        return;
                    }
                    success(json.location);
                };
                formData = new FormData();
                formData.append('file', blobInfo.blob(), blobInfo.filename());
                xhr.send(formData);
            },
            menubar: false,
            toolbar_items_size: 'small',
            language: 'zh_CN',
        });


        // 年选择器
        laydate.render({
            elem: '#EDStudentForm input[name="schoolYear"]',
            type: 'year',
            trigger: 'click'
        });

    });
</script>

<link rel="stylesheet" href="{{ asset('/admin/libs/sku/sku_style.css') }}"/>
<link rel="stylesheet" href="{{ asset('/admin/libs/selectpage/selectpage.css') }}"/>
<script>


</script>
</body>
</html>